#coding=utf-8
import os
import sys
from jinja2 import Environment  
from jinja2 import FileSystemLoader  
import jinja2
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)


def sortedDictValues3(adict): 
	keys = adict.keys() 
	keys.sort() 
	return map(adict.get, keys)

#lua 生成器
def readAllTxt(filename,root):
	global connconfig
	txtfile = "/Users/kaixin/Desktop/txt/txt/" + filename
	file_object = open(txtfile)
	try:
	    all_the_text = file_object.read( )
	finally:
	    file_object.close()
	cellType={}
	
	all_the_text = all_the_text.split("#")
	Cellkeys = all_the_text[0].split("@")

	allTables = []
	for index in range(1, len(all_the_text)):
		rowtxt = all_the_text[index].split("@")
		rowdata = {}
		for index0 in range(0, len(rowtxt)):
			rowdata[Cellkeys[index0]] = rowtxt[index0]
		if str(rowtxt[0]) != "":
			allTables.append(rowdata)

	TemplateLoader = jinja2.FileSystemLoader(searchpath='./template')
	TemplateEnv = jinja2.Environment(loader=TemplateLoader)	  
	template = TemplateEnv.get_template('config.txt') 

	if not os.path.exists(root):
		os.mkdir(root)

	file_object = open(root + filename[0:len(filename) - 4] + ".lua", 'w')

	file_object.write(template.render(datas = allTables,keys = Cellkeys[2:]))
	file_object.close()
	print(root + filename[0:len(filename) - 4] + ".lua")

if __name__ == '__main__':
	allConfig = []
	baseURL = "/Users/kaixin/Desktop/txt"
	for root, subdirs, files in os.walk(baseURL + "/txt/"):
		for file in files:
			if file.endswith(".txt"):
				readAllTxt(file,root.replace("txt","config") + "/")
				allConfig.append(file[0:len(file) - 4])
				pass
	TemplateLoader = jinja2.FileSystemLoader(searchpath='./template')
	TemplateEnv = jinja2.Environment(loader=TemplateLoader)	  
	template = TemplateEnv.get_template('allconfig.txt')  
	file_object = open("/Users/kaixin/Desktop/txt/lua/allConfig.lua", 'w')
	file_object.write(template.render(datas = allConfig))
	file_object.close()